package com.qf.day0614.controller;

import com.qf.day0614.entity.User;
import com.qf.day0614.service.UserService;
import com.qf.day0614.utils.RedisLock;
import com.qf.day0614.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/15 14:25
 * @Version v1.8
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedisLock redisLock;

    @PostMapping("/delete")
    public ResultVo deleteUser(User user){
        userService.removeById(user);
        User o = (User) redisTemplate.opsForValue().get(user.getId());
        if (o!=null){
            redisTemplate.delete(user);
        }
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(1);
        resultVo.setMsg("成功删除");
        return resultVo;
    }

    /**
     * 修改用户信息
     * 需要同时把缓存的用户信息修改
     * @param user
     * @return
     */
    @PostMapping("/update")
    public ResultVo updateUser(@RequestBody User user){

        userService.updateById(user);
        User o = (User) redisTemplate.opsForValue().get("user:" + user.getId());
        if (o!=null){
            o.setName(user.getName());
            o.setAge(user.getAge());
            o.setEmail(user.getEmail());
            redisTemplate.opsForValue().set("user:"+user.getId(),o, Duration.ofMinutes(10));
        }
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(1);
        resultVo.setMsg("更新成功");
        resultVo.setData(user);
        return resultVo;
    }

    @GetMapping("/login")
    public ResultVo login(String username,String password){
        String key = "user:"+username;
        User o = (User) redisTemplate.opsForValue().get(key);
        if (o!=null){
            System.out.println(o);
        }

        ResultVo resultVo = new ResultVo();
        resultVo.setCode(1);
        resultVo.setMsg("登录成功");
        return resultVo;
    }

    @PostMapping("/register")
    public ResultVo register(@RequestBody User user){
        //申请分布式锁
        redisLock.lock("user:register:lock");
        //1.省略一些细节
        userService.save(user);
        //2.写入redis
        String key = "user:"+user.getName();
        redisTemplate.opsForValue().set(key,user);

        //释放锁
        redisLock.unlock("user:register:lock");

        ResultVo resultVo = new ResultVo();
        resultVo.setCode(1);
        resultVo.setMsg("注册成功");
        resultVo.setData(user);
        return resultVo;
    }

}
